package com.wwl.open.util;

import com.wwl.open.entity.Monitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.hardware.Sensors;
import oshi.software.os.OSFileStore;

import java.time.LocalDateTime;

public class ResourceMonitorUtil {

    private static final Logger logger = LoggerFactory.getLogger(ResourceMonitorUtil.class);

    public static Monitor getLatestMonitor() {
        SystemInfo si = new SystemInfo();
        HardwareAbstractionLayer hal = si.getHardware();

        // 内存
        GlobalMemory memory = hal.getMemory();
        double memTotal = memory.getTotal() / 1e9;
        double memUsed = (memory.getTotal() - memory.getAvailable()) / 1e9;
        double memUsage = (memUsed / memTotal) * 100;

        // CPU
        CentralProcessor cpu = hal.getProcessor();
        // 1. 第一次获取 CPU "Ticks"（时间片统计）
        long[] prevTicks = cpu.getSystemCpuLoadTicks();
        // 2. 等待一段时间（例如 1 秒）
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 3. 第二次获取 Ticks 并计算 CPU 使用率
        double cpuUsage = cpu.getSystemCpuLoadBetweenTicks(prevTicks) * 100;

        Sensors sensors = hal.getSensors();
        double cpuTemp = sensors.getCpuTemperature();

        // 存储
        long storageTotal = 0, storageUsed = 0;
        for (OSFileStore fs : si.getOperatingSystem().getFileSystem().getFileStores()) {
            storageTotal += fs.getTotalSpace();
            storageUsed += (fs.getTotalSpace() - fs.getUsableSpace());
        }
        double storageTotalGB = storageTotal / 1e9;
        double storageUsedGB = storageUsed / 1e9;
        double storageUsage = (storageUsed * 100.0) / storageTotal;

        logger.info("内存：已用{}GB，总共{}GB，使用率{}%", memUsed, memTotal, memUsage);
//        logger.info("CPU：使用率{}%，温度:{}°C", cpuUsage, cpuTemp);
//        logger.info("存储：已用{}GB，总共{}GB，使用率{}%", storageUsedGB, storageTotalGB, storageUsage);

        Monitor monitor = new Monitor();
        monitor.setMemTotal(memTotal);
        monitor.setMemUsed(memUsed);
        monitor.setMemUsageRate(memUsage);
        monitor.setCpuUsageRate(cpuUsage);
        monitor.setCpuTemperature(cpuTemp);
        monitor.setStorageTotal(storageTotalGB);
        monitor.setStorageUsed(storageUsedGB);
        monitor.setStorageUsageRate(storageUsage);
        monitor.setTimestamp(LocalDateTime.now());
        return monitor;
    }
}
